package com.apollow.oschina.adapter;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import com.apollow.oschina.base.BaseFragment;
import java.util.ArrayList;
import java.util.List;

//ViewPager的适配器的抽取;
    public class TabVPAdpater extends FragmentStatePagerAdapter {
        private List<Class<? extends BaseFragment>> pagers=new ArrayList<>();
        private List<String> titles=new ArrayList<>();
        private  List<Bundle> bundles=new ArrayList<>();
        private Context context ;
        public void addFragments(Class<? extends  BaseFragment> clz){
            pagers.add(clz);
            notifyDataSetChanged();
        }
        //添加片段
        public void addFragments(List<Class<? extends  BaseFragment>> clzs){
            pagers.addAll(clzs);
            notifyDataSetChanged();
        }
        public TabVPAdpater(FragmentManager fm, ViewPager viewpager, TabLayout tablayout) {
            super(fm);
            //4. 将数据适配器设置给ViewPager
            viewpager.setAdapter(this);
            //5. Tablayout要和ViewPager要绑定/关联
            tablayout.setupWithViewPager(viewpager);
            context=viewpager.getContext();
        }
        @Override
        public Fragment getItem(int position) {
            /**通过片段字节码构建片段对象
             * context：上下文
             * fileName：类名
             * bundle:要传递给片段的参数
             */
            Fragment fragment=Fragment.instantiate(context,pagers.get(position).getName(),bundles.get(position));
            return fragment;
        }
        @Override
        public int getCount() {
            return pagers.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);
        }
        /**
         * 添加tab
         *  title:页签的标题
         *  class ：页签关联的fragment的class
         *  bundle：向关联的fragment传递的参数
         */
        public void addTab(String title, Class<? extends  BaseFragment> clz, Bundle args) {
            titles.add(title);
            addFragments(clz);
            bundles.add(args);
        }
    }